package com.wuye.web;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.net.URL;
import java.util.HashSet;
import java.util.Properties;
import java.util.Set;

/**
 * Created by Administrator on 2015/1/26.
 */
public class WebUtils implements InitializingBean {

    public static void setRequestParameter(Object object, HttpServletRequest request) {
        Set<String> sets = request.getParameterMap().keySet();
        Field fs[] = object.getClass().getDeclaredFields();
        for (Field f : fs) {
            f.setAccessible(true);
            if (sets.contains(f.getName())) {
                String val = request.getParameter(f.getName());
                try {
                    if (f.getType() == String.class) {
                        f.set(object, val);
                    } else if (f.getType() == int.class || f.getType() == Integer.class) {
                        if (val != null && LangUtil.isNum(val)) {
                            f.set(object, Integer.parseInt(val));
                        } else {
                            f.set(object, 0);
                        }
                    } else if (f.getType() == long.class || f.getType() == Long.class) {
                        if (val != null && LangUtil.isNum(val)) {
                            f.set(object, Long.parseLong(val));
                        } else {
                            f.set(object, 0l);
                        }
                    } else {
                        System.err.println("TODO:" + f.getType());
                        throw new RuntimeException("没有实现的方法");
                    }
                    sets.remove(f.getName());
                } catch (Exception e) {
                    System.err.println("TODO:orderState=" + val + ";" + f.getType().getName() + ";" + f.getName());
                    e.printStackTrace();
                }
            }
        }
        if (sets.size() > 0) {
            Method[] ms = object.getClass().getMethods();
            for (String s : sets) {
                String key = "set" + s.toLowerCase().replaceAll("[-]", "").replaceAll("[.]", "").replaceAll("[:]", "");
                String val = request.getParameter(s);
                fk:
                {
                    for (Method m : ms) {
                        try {
                            if (m.getParameterTypes().length == 1) {
                                if (m.getName().toLowerCase().equals(key)) {
                                    Class type = m.getParameterTypes()[0];
                                    if (type == String.class) {
                                        m.invoke(object, val);
                                    } else if (type == int.class || type == Integer.class) {
                                        if (val != null && LangUtil.isNum(val)) {
                                            m.invoke(object, Integer.parseInt(val));
                                        } else {
                                            m.invoke(object, 0);
                                        }
                                    } else if (type == long.class || type == Long.class) {
                                        if (val != null && LangUtil.isNum(val)) {
                                            m.invoke(object, Long.parseLong(val));
                                        } else {
                                            m.invoke(object, 0l);
                                        }
                                    } else if (type == double.class || type == Double.class) {
                                        if (val != null) {
                                            m.invoke(object, Double.parseDouble(val));
                                        } else {
                                            m.invoke(object, 0l);
                                        }
                                    } else {
                                        System.err.println("TODO:" + type.getName());
                                        throw new RuntimeException("没有实现的方法");
                                    }
                                    break fk;
                                }
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                    System.err.println("没有找到方法:" + key);
                }
            }
        }
    }


    public static String getSmsRandom(int len) {
        String t = String.valueOf(System.nanoTime());
        return t.substring(t.length() - len);
    }

    /**
     * 获得文件路径前传
     *
     * @param userId
     * @return
     */
    public static String getSpit3Path(long userId) {
        return userId / 100 * 1000 + "/" + userId / 1000 + "/" + userId;
    }


    public static String getSpit3Path(String cmd5) {
        return cmd5.substring(0, 3) + "/" + cmd5.substring(3, 6) + "/" + cmd5.substring(6);
    }


    @Autowired
    private ApplicationContext context;


    public static void beanBindToServletContext(ApplicationContext context, String filter) {
        ServletContext sc = context.getBean(ServletContext.class);
        String names[] = context.getBeanDefinitionNames();
        for (String name : names) {
            if (name.endsWith(filter)) {
//                log.info("----register " + filter + " :" + name);
                sc.setAttribute(name, context.getBean(name));
            }
        }
    }


    @Override
    public void afterPropertiesSet() throws Exception {
//        log.info("=====================WebUtil 初始化.web jsp 注入spring repository/web bean.===================");

        ServletContext sc = context.getBean(ServletContext.class);
        beanBindToServletContext(context, "Repository");
        beanBindToServletContext(context, "Service");
    }

}
